package bittorrent;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;

public class Peer {
    /* atribut - atribut yang dimiliki oleh Peer */
        private String trackerAddress;
        private InetSocketAddress ip_port = null;

    /* constructor */
        public Peer () {}                       //default ctor
        public Peer (String trackerAddress) {   //user defined ctor
            this.trackerAddress = trackerAddress;
        }

    /* setter */
        public void setHostAddr (InetSocketAddress ip_port) {
            this.ip_port = ip_port;
        }

    /* method - method yang dimiliki oleh Peer */
        //@param filename - nama file metainfo .torrent yang ingin diunduh oleh peer dari peer lain dan akan dikirimkan kepada tracker
        public Response setHTTPGetRequest_getHTTPGetResponse (String filename) {
            try {
                Torrent torrent = new Torrent(filename);
                Request req = new Request(torrent);
                Response response = new Response(sendHTTPGetRequest_receiveHTTPGetResponse("http://" + this.trackerAddress + ":" + Request.trackerPort, req.encodeRequest()));
                return (response);
            } catch (Exception e) {
                return (null);
            }
        }

        private static String sendHTTPGetRequest_receiveHTTPGetResponse (String announce, String requestParameters) {
            String response = null;
            if (announce.startsWith("http://")) {
                //send an HTTP Get Request to the servlet
                try {
                    //construct data
                    StringBuilder data = new StringBuilder();
                    //send data
                    String urlStr = announce;
                    if ((requestParameters != null) && (requestParameters.length() > 0)) {
                        urlStr += "?" + requestParameters;
                    }
                    URL url = new URL(urlStr);
                    URLConnection conn = url.openConnection();
                    //get the response
                    BufferedReader buffreadr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = buffreadr.readLine()) != null) {
                        data.append(line);
                    }
                    buffreadr.close();
                    response = data.toString();
                } catch (Exception e) {
                }
            }

            return (response);
        }
}
